﻿jQuery.extend(
{
    rndm: function (i) { return Math.floor(i * (Math.random() % 1)) },
    rndMU: function (min, max) { return min + jQuery.rndm(max - min + 1) }
});

(function ($) {
    $.cookie = (function (key, value, options) {
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }
        options = value || {};
        var decode = options.raw ? function (s) { return s; } : decodeURIComponent;
        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    });
})(jQuery);

$(document).ready(function () {
    var $carpet = $('#carpet'),
		$drg = $carpet.find('.drg'),
        $dst = $carpet.find('.dust'),
        $ft = $('#foot'),
		tzX = ($carpet.width() - 50),
		tzY = ($carpet.height() - 50),
		i = 0, elmObj = {},
		d = new Date(),
        hidethem = new Array();

    //$('#year').text(d.getFullYear());

    var appElm = (function (elmObj) {
        var tag = '<dd/>',
				css = elmObj.uidclass,
				html = elmObj.uidhtml;

        $(tag, { 'class': css, id: elmObj.id }).html(html).appendTo(elmObj.elm).draggable(
			{
			    revert: 'invalid',
			    containment: '#room',
			    addClasses: false
			});
    });

    $.each($drg, function () {
        $(this).attr('id', 'toy' + (i));

        var yos = $.rndMU(0, tzY),
			xos = $.rndMU(0, tzX),
			idd = $(this).attr('id'),
			clss = $(this).attr('class'),
			cntnt = $(this).html(),
			cook = $.cookie(idd),
			trash = $.cookie(idd + 'del'),
			app,
			ttg = (function () {
			    if (cook) { app = '#' + cook; return '<dd/>'; }
			    if (trash) { app = '#' + trash; return '<div/>'; }
			});

        if (ttg()) {
            $('#' + idd).remove();
            $(ttg(), { 'class': clss, id: idd }).html(cntnt).appendTo(app).draggable(
			{
			    revert: 'invalid',
			    containment: '#room',
			    addClasses: false
			});
        }
        else $(this).css({ position: 'absolute', left: xos + 'px', top: yos + 'px' });
        i++
    });

    $(function () {
        $('#carpet').droppable(
		{
		    accept: '.drg',
		    addClasses: false,
		    drop: function (e, ui) {
		        $.cookie(ui.draggable.attr('id'), null);
		        $.cookie(ui.draggable.attr('id') + 'del', null)
		    }
		});

        $('#balls').droppable(
		{
		    accept: '.ball,.balloon',
		    activeClass: 'shelfactive',
		    hoverClass: 'shelfhover',
		    addClasses: false,
		    drop: function (e, ui) {
		        elmObj =
				{
				    id: ui.draggable.attr('id'),
				    uidclass: ui.draggable.attr('class'),
				    uidhtml: ui.draggable.html(),
				    elm: $(this),
				    elmid: $(this).attr('id')
				}
		        $.cookie(elmObj.id, 'balls');
		        $.cookie(elmObj.id + 'del', null);
		        ui.draggable.remove();
		        appElm(elmObj)
		    }
		});

        $('#cars').droppable(
		{
		    accept: '.citroen,.ferrari',
		    activeClass: 'shelfactive',
		    hoverClass: 'shelfhover',
		    addClasses: false,
		    drop: function (e, ui) {
		        elmObj =
				{
				    id: ui.draggable.attr('id'),
				    uidclass: ui.draggable.attr('class'),
				    uidhtml: ui.draggable.html(),
				    elm: $(this),
				    elmid: $(this).attr('id')
				}
		        $.cookie(elmObj.id, 'cars');
		        $.cookie(elmObj.id + 'del', null);
		        ui.draggable.remove();
		        appElm(elmObj)
		    }
		});

        $('.dust').droppable(
		{
		    accept: '.drg',
		    addClasses: false,
		    drop: function (e, ui) {
                hidethem.push(ui.draggable);
                $('#hidethemall').css({'display':'inline-block','background':'#fff','cursor':'pointer','color':'red','font-weight':'bold','float':'right'});
		        $.cookie(ui.draggable.attr('id'), null);
		        ui.draggable.remove(),
				$(this).addClass('full');
		        $.cookie(ui.draggable.attr('id') + 'del', 'foot')
		    }
		});

        $($drg).draggable(
		{
		    revert: 'invalid',
		    containment: '#room',
		    addClasses: false,
		    cursorAt: { left: 25, top: 25 }
		});

        $('#hidethemall').click(function()
        {
            if (hidethem.length > 0)
            {
                for (var c=0; c<hidethem.length; c++)
                {
                    elmObj =
				    {
				        id: $(hidethem[c]).attr('id'),
				        uidclass: $(hidethem[c]).attr('class'),
				        uidhtml: $(hidethem[c]).html(),
				        elm: $('#foot'),
				        elmid: $('#foot').attr('id')
				    }
                    appElm(elmObj);
                    $('#hidethemall').hide();
                    $dst.removeClass('full')
                }
                hidethem = [];
            }
        });
    });
});